import {onActivated, onDeactivated, onMounted, onUnmounted, ref} from "vue";
import {throttle} from "underscore";

export default function (elRef) {
   let el = window
   let elDoc = document.documentElement

   //滚动高度
   const scrollTop = ref(0)
   //可滚动高度
   const scrollHeight = ref(0)
   //窗口高度
   const clientHeight = ref(0)

   //监听是否滚动到底部
   const isBottom = ref(false)

   //节流监听页面滚动
   const scrollListenerHandler = throttle(() => {
      clientHeight.value = elDoc.clientHeight
      scrollTop.value = elDoc.scrollTop
      scrollHeight.value = elDoc.scrollHeight

      //请求更多房源信息
      if (scrollTop.value + clientHeight.value === scrollHeight.value) {
         isBottom.value = true
      }
   }, 100)

   //创建组件时开启监听
   onMounted(() => {
      if (elRef) {
         el = elRef.value
         elDoc = el
      }
      el.addEventListener('scroll', scrollListenerHandler)
   })
   //销毁组件时移除监听
   onUnmounted(() => {
      el.removeEventListener('scroll', scrollListenerHandler)
   })

   //页面活跃时开启监听
   onActivated(() => {
      //恢复离开时的滚动高度
      elDoc.scrollTop = scrollTop.value
      el.addEventListener('scroll', scrollListenerHandler)
   })
   //页面不活跃时移除监听
   onDeactivated(() => {
      el.removeEventListener('scroll', scrollListenerHandler)
   })

   return {isBottom, scrollTop, scrollHeight, clientHeight}
}